<template>
  <div class="container">
       <!-- 团课课程  按钮部分 -->
       <div>
        <el-button  type="primary" @click="addCourse(courseFormDataRef)"  color="#409EFF" style=" color:white;">添加课程</el-button>
      </div>
       <el-divider></el-divider>
       <!-- 课程列表 -->
       <el-table :data="currentTableData" border style="width: 100%"    >
            <el-table-column prop="name" sortable label="课程名称"  />
            <el-table-column prop="duration" sortable label="时长(分钟)"  />
            <el-table-column prop="contains" sortable label="上课容纳人数" />
            <el-table-column label="操作" width="250">
                 <template #default="scope">
                      <el-row class="btn-opt">
                        <el-button  size="small" type="primary"  @click="handleEdit(scope.row)" >
                          编辑<el-icon><Edit /></el-icon>
                        </el-button>
                        <el-button size="small" type="primary" color="#ED5565" style=" color:white;" @click="handleDelete(scope.row)"   >
                          删除<el-icon><CloseBold /></el-icon>
                        </el-button>
                      </el-row>
                 </template>
            </el-table-column>
       </el-table>

       <!-- 分页组件 -->
       <div class="pagination-container">
    <el-pagination small background layout="prev, pager, next" :total="totalItems"
            v-model:current-page="currentPage" @current-change="handelCurrentChange" :hide-on-single-page="paginationShow"
            style="margin-top: 20px;" />
    </div>  
       <!--添加修改的组件  -->
       <!-- 添加或者修改课程 -->
       <el-drawer v-model="addEditDrawer" direction="rtl" size="80%" >
            <template #header>
                 <h2>{{ drawerTitle }}</h2>
            </template>
            <el-form
     ref="courseFormDataRef"
      :model="courseFormData"
      label-width="120"
      :rules="rules"
     
    >
     <el-form-item prop="name" label="课程名称">
            <el-input v-model="courseFormData.name"  placeholder="请输入课程名称" style="width:90%"/>
      </el-form-item>
      <el-form-item label="时长(分钟)">
           <el-input-number
              v-model="courseFormData.duration"
              :min="0"
              controls-position="right"
              class="w40"
          />
      </el-form-item>
      <el-form-item label="课堂容纳人数">
           <el-input-number
              v-model="courseFormData.contains"
              :min="0"
              controls-position="right"
              class="w40"
          />
      </el-form-item>
      <el-form-item label="消耗次数/节">
           <el-input-number
              v-model="courseFormData.timesCost"
              :min="1"
              controls-position="right"
              class="w40"
          />
      </el-form-item>
      <el-form-item label="课程颜色">
      <el-color-picker v-model="courseFormData.color"  />
      </el-form-item>
      <el-form-item label="支持课程">
         <el-table
           ref="multipleTableRef"
           :header-cell-style="{ background: '#F2F2F2', color: '#333' }"
          :data="courseList"
          style="width: 90%"
          size="small"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="100" />
          <!-- <el-table-column label="编号" prop="id"/> -->
          <el-table-column property="cardName" sortable label="会员卡"  />
          <el-table-column property="cardType" sortable label="会员卡类型" />
        </el-table>
      </el-form-item>
      <el-form-item label="课程描述">
          <WangEditor v-model:modelValue="courseFormData.introduce" class="editor-big"/>
      </el-form-item>
        <div  class="form-div">高级功能(对预约会员条件的限制)</div>
       <el-form-item label="限制性别">
          <template #label>
              <h1>限制性别</h1>
          </template>
            <el-select v-model="courseFormData.limitSex" placeholder="无限制" class="w20">
              <el-option label="无限制" value="null" />
              <el-option label="男" value="男" />
              <el-option label="女" value="女" />
            </el-select> 
      </el-form-item>
       <el-form-item label="限制年龄" > 
           <template #label><h1>限制年龄</h1></template>
          <el-radio v-model="courseFormData.limitAge"  value="0" >不限制</el-radio>
       </el-form-item>
       <el-form-item label="  ">
          <el-radio v-model="courseFormData.limitAge" :value="courseFormData.limitAge">
              <el-input v-model="courseFormData.limitAge" style="width:250px">
              <template #prepend>
              <span>大于</span>
              </template>
              <template #append>
              <span>岁</span>
              </template>
              </el-input>
          </el-radio>
        
      </el-form-item>
       <el-form-item label="限制次数">
          <template #label><h1>限制次数</h1></template> 
         <el-radio v-model="courseFormData.limitCounts"  value="0" >不限制</el-radio>
      </el-form-item>
       <el-form-item label="  ">
         <el-radio v-model="courseFormData.limitCounts" :value="courseFormData.limitCounts">
           <!-- <span class="form-span">每名会员最多可以预约本课程</span> -->
            <el-input v-model="courseFormData.limitCounts"  style="width:350px">
            <template #prepend>
            <span>每名会员最多可以预约本课程</span>
            </template>
            <template #append>
            <span>次</span>
            </template>
            </el-input>
            <!-- <span class="form-span">次</span> -->
        </el-radio>     
      </el-form-item>
    
      <el-form-item>
        <div v-if="submit">
                <el-button type="primary" @click="submitForm(courseFormDataRef)">
                添加
                </el-button>
                <el-button @click="resetForm(courseFormDataRef)">重置</el-button>
              </div>
                
              <div v-else>
                <el-button type="primary" @click="changeForm(courseFormDataRef) ">
                保存
              </el-button>
              <el-button @click="outForm(courseFormDataRef)">取消</el-button>
              </div>
      </el-form-item>
      </el-form>
       </el-drawer>
  </div>
</template>

<script setup>
import { ref , reactive , watch , computed , onMounted, toRaw } from 'vue'
import {Edit,CloseBold} from '@element-plus/icons-vue'
import { ElMessageBox } from 'element-plus'
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import GLOBAL from '@/api/global_variable'
import WangEditor from '@/components/WangEditor.vue'
import { handleGroupClassSubmit as GroupClassApi } from '../../api/groupClass'
import { handleGroupClassData } from '../../api/groupClass'
import {handleGroupClassDelete} from '../../api/groupClass'
import { handleGroupClassEdit } from '../../api/groupClass'




const currentTableData = ref([])
const currentPage = ref(1)
const pageSize = 10
const totalItems = ref(0)
const paginationShow = ref(true)
const namelist=ref([])
const tableData = ref([])
const uid=ref(0)

watch(tableData, (newVal, oldVal) => {
    currentPage.value = 1
    totalItems.value = tableData.value.length
    currentTableData.value = tableData.value.filter((item, index) => index < pageSize)
    if(tableData.value.length!=0){
      uid.value=tableData.value[(Math.ceil(totalItems.value-1))??0].id
    }
    console.log("开始")
    console.log(uid.value)
    console.log(currentPage.value)
    console.log(currentTableData.value)
    console.log(totalItems.value)
    console.log("结束")
    paginationShow.value = tableData.value.length > 10 ? true : false
})

const handelCurrentChange = page => {
    currentPage.value = page
    // currentPage.value = 1
    const index = pageSize * (page - 1)
    const nums = pageSize * page
    const tables = []
    for (let i = index; i < nums; i++) {
        if (tableData.value[i]) tables.push(tableData.value[i])
    }
    currentTableData.value = tables
    console.log(currentTableData.value)
}
function handelCurrentChange2 () {
  totalItems.value=tableData.value.length
  const page=Math.ceil(totalItems.value/pageSize)
  console.log(totalItems.value)
  console.log("page="+page)
    currentPage.value = page
    // currentPage.value = 1
    const index = pageSize * (page - 1)
    const nums = pageSize * page
    const tables = []
    for (let i = index; i < nums; i++) {
        if (tableData.value[i]) tables.push(tableData.value[i])
    }
    currentTableData.value = tables
    console.log(currentTableData.value)
}

function handelCurrentChange3 () {
  totalItems.value=tableData.value.length
  if(currentTableData.value.length==0 && currentPage.value!=0){
    GLOBAL.page=currentPage.value-1
  }
  else{
    GLOBAL.page=currentPage.value
  }
  const page=GLOBAL.page
  console.log(totalItems.value)
  console.log("page="+page)
    currentPage.value = page
    // currentPage.value = 1
    const index = pageSize * (page - 1)
    const nums = pageSize * page
    const tables = []
    for (let i = index; i < nums; i++) {
        if (tableData.value[i]) tables.push(tableData.value[i])
    }
    currentTableData.value = tables
    console.log(currentTableData.value)
}

const getData = async () => {
    try {
        const { data } = await handleGroupClassData()
        console.log(data)
        tableData.value = data
        console.log(tableData.value)
        for (let i in tableData.value){
          namelist.value.push(tableData.value[i].name)
        }
    } catch (error) {
        ElMessage.error('请求接口报错')
        console.log(error)
    }
}

onMounted(async () => {
    getData()

}) 


//添加或者修改的抽屉
const addEditDrawer = ref(false)
const drawerTitle = ref('')

//传给表单的信息  
const courseFormData = reactive({
  id:'',
 name:'', 
 duration:null,  
 contains:null, 
 timesCost:null,   
 color:'',   
 memberCardData:'',   
 introduce:'',   
 limitSex:'',     
 limitAge:'',  
 limitCounts:'',
})
const submit = ref(true)
//点击添加会员卡的按钮触发的事件
const addCourse = () => {
  console.log('-----------新增课程--------------')
  addEditDrawer.value = true
  drawerTitle.value = '新增课程'
  //清空数据 
  function funct(){
        submit.value=true
    }
    funct()
  uid.value=Math.ceil(uid.value+1)
courseFormData.id=uid
 courseFormData.name='' 
 courseFormData.duration=null  
 courseFormData.contains= null   
 courseFormData.timesCost= null     
 courseFormData.color=''   
 courseFormData.memberCardData=[]   
 courseFormData.introduce=''   
 courseFormData.limitSex=''     
 courseFormData.limitAge='' 
 courseFormData.limitCounts=''
}

  //表单验证规则
  const rules=reactive({
      name:[
          {required: true,message: '请输入课程名',trigger: 'blur',},
      ],
      limitAge:[
          {required: true,message: '请输入年龄',trigger: 'blur',},
      ],
      limitSex:[
          {required: true,message: '请输入性别',trigger: 'blur',},
      ],
      limitCounts:[
          {required: true,message: '请输入次数',trigger: 'blur',},
      ],
  })
  const courseFormDataRef=ref()
  
  //拿到表格对象
  const multipleTableRef = ref()
  //to 支持的课程需要调用接口 获取相关数据
  const  courseList = [
      {id:1,cardName:'金卡',cardType:'次卡(有限期)'},
      {id:2,cardName:'体验卡卡',cardType:'次卡(有限期)'},
      {id:3,cardName:'至尊卡',cardType:'次卡(无限期)'},
      {id:4,cardName:'测试卡',cardType:'次卡(有限期)'},
      {id:5,cardName:'超级卡',cardType:'次卡(无限期)'},
      {id:6,cardName:'测试卡1',cardType:'次卡(有限期)'},
  ]
  //当表格多选发生改变的时候 调用的方法
  const  handleSelectionChange = (val)=>{
       console.log('----val----',val)
       courseFormData.memberCardData=val
  }
  //保存添加或者修改会员开的数据 
  const submitForm = async (formElement) => {
    console.log('=========添加或者修改课程========')
    console.log("tableData1"+tableData.value)
    
    console.log(formElement)
    console.log(currentTableData.value)
    console.log("courseFormData"+courseFormData.memberCardData)
    if (!formElement) return
    //进行验证courseFormData
    await formElement.validate((valid, fields) => {
        if (valid) {
            console.log('submit!')
            if(courseFormData.limitAge==''){
              courseFormData.limitAge=0
            }
            if(courseFormData.limitCounts==''){
              courseFormData.limitCounts=0
            }
            GroupClassApi({name:courseFormData.name,duration:courseFormData.duration,contains:courseFormData.contains,timesCost:courseFormData.timesCost,color:courseFormData.color,
              introduce:courseFormData.introduce,limitSex:courseFormData.limitSex,limitAge:courseFormData.limitAge,limitCounts:courseFormData.limitCounts
            }).then(res=>{
                console.log("这也是返回值"+res.status)
                if(res.status==200){
                  addEditDrawer.value = false
                  tableData.value.push({id:uid.value,name:courseFormData.name,duration:courseFormData.duration,contains:courseFormData.contains,timesCost:courseFormData.timesCost,color:courseFormData.color,
              memberCardData:courseFormData.memberCardData,introduce:courseFormData.introduce,limitSex:courseFormData.limitSex,limitAge:courseFormData.limitAge,limitCounts:courseFormData.limitCounts})
              currentTableData.value.push({id:uid.value,name:courseFormData.name,duration:courseFormData.duration,contains:courseFormData.contains,timesCost:courseFormData.timesCost,color:courseFormData.color,
                memberCardData:courseFormData.memberCardData,introduce:courseFormData.introduce,limitSex:courseFormData.limitSex,limitAge:courseFormData.limitAge,limitCounts:courseFormData.limitCounts})
                  handelCurrentChange2 ()
                 // namelist.value.push(courseFormData.name)
                 console.log(".............................."+uid.value)
                  console.log(courseFormData)
                  console.log(tableData.value)
                  console.log(currentTableData.value)
                  ElMessageBox.alert('添加成功！', '添加成功', {
                      type: 'success',
                      center:true,
                  })
                }
                else{
                    ElMessageBox.alert('添加失败！', '添加失败', {
                        type: 'error',
                    })
                }
            })

            // todo 这里去提交表单数据到后端
            
            // ...

        } else {
            console.log('表单验证失败，请重新填写', fields)
        }
    })
}
  //取消 
  const resetForm = () => {
  courseFormData.name='' 
 courseFormData.duration=null  
 courseFormData.contains= null   
 courseFormData.timesCost= null     
 courseFormData.color=''   
 courseFormData.memberCardData=[]   
 courseFormData.introduce=''   
 courseFormData.limitSex=''     
 courseFormData.limitAge='' 
 courseFormData.limitCounts=''
}



//点击编辑按钮触发的事件
const handleEdit = (row) => {
  //changerules(2)
  console.log(rules)
    //修改抽屉title
    console.log('-----------编辑课程--------------')
  addEditDrawer.value = true
  console.log(row.name)
  console.log(tableData.value)
  drawerTitle.value = '编辑课程'

    function funct(){
        submit.value=false
    }
    funct()
    //给表单元素赋值
    courseFormData.id=row.id
    courseFormData.name=row.name
 courseFormData.duration=row.duration
 courseFormData.contains=row.contains
 courseFormData.timesCost=row.timesCost   
 courseFormData.color=row.color 
 courseFormData.memberCardData=row.memberCardData
 courseFormData.introduce=row.introduce
 courseFormData.limitSex=row.limitSex 
 courseFormData.limitAge=row.limitAge
 courseFormData.limitCounts=row.limitCounts
    //todo ...
    console.log("...........................................................")
    GLOBAL.index=tableData.value.indexOf(tableData.value.filter(item => item.id === row.id)[0]);
    console.log(GLOBAL.index)
    GLOBAL.id=tableData.value[GLOBAL.index].id
    console.log(GLOBAL.id)
}



const changeForm = async (formElement,row) => {
    console.log(formElement)
   


    if (!formElement) return
    //进行验证
    await formElement.validate((valid, fields) => {
        if (valid) {
            console.log('change!')
            console.log(row)
            console.log(tableData)
            console.log(GLOBAL.id)
            // todo 这里去提交表单数据到后端
            console.log(courseFormData.limitAge)
            handleGroupClassEdit({id:GLOBAL.id,name:courseFormData.name,duration:courseFormData.duration,contains:courseFormData.contains,timesCost:courseFormData.timesCost,color:courseFormData.color,
              introduce:courseFormData.introduce,limitSex:courseFormData.limitSex,limitAge:courseFormData.limitAge,limitCounts:courseFormData.limitCounts
            }).then(res=>{
                console.log(res)
                if(res.status==200){
                  addEditDrawer.value = false
    tableData.value.splice(GLOBAL.index,1,{name:courseFormData.name,duration:courseFormData.duration,contains:courseFormData.contains,timesCost:courseFormData.timesCost,color:courseFormData.color,
      memberCardData:courseFormData.memberCardData,introduce:courseFormData.introduce,limitSex:courseFormData.limitSex,limitAge:courseFormData.limitAge,limitCounts:courseFormData.limitCounts})
                  currentTableData.value.splice(Math.ceil(GLOBAL.index%pageSize),1,{name:courseFormData.name,duration:courseFormData.duration,contains:courseFormData.contains,timesCost:courseFormData.timesCost,color:courseFormData.color,
                    memberCardData:courseFormData.memberCardData,introduce:courseFormData.introduce,limitSex:courseFormData.limitSex,limitAge:courseFormData.limitAge,limitCounts:courseFormData.limitCounts})
                  ElMessageBox.alert('修改成功！', '修改成功', {
                        type: 'success',
                        center:true,
                    })
                }
                else{
                    ElMessageBox.alert('修改失败！', '修改失败', {
                        type: 'error',
                    })
                }
            })
            // ...

        } else {
            console.log('表单验证失败，请重新填写', fields)
        }
    })
}

const outForm = (formElement) => {
  const row=tableData.value[GLOBAL.index]
  courseFormData.name = row.name
    courseFormData.phone = row.phone
    courseFormData.email= row.email
    courseFormData.introduce=row.introduce
    courseFormData.birthday=row.birthday
    courseFormData.sex=row.sex

}


//点击删除按钮触发的事件
const handleDelete = (row) => {
  //changerules(2)
  console.log("...........................................................")
    GLOBAL.index=tableData.value.indexOf(tableData.value.filter(item => item.id === row.id)[0]);
    console.log(GLOBAL.index)
    GLOBAL.id=tableData.value[GLOBAL.index].id
    console.log(GLOBAL.id)
  ElMessageBox.confirm(
    '确认删除此老师信息吗?删除成功后将无法恢复，请谨慎操作！',
    '删除确认',
    {
    dangerouslyUseHTMLString: true,
      type: 'warning',
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      center:true,
      
    }
  )
  .then(() => {
    const index2 = currentTableData.value.indexOf(row);
    const index = index2+(currentPage.value-1)*pageSize;
    console.log("这是row"+row)
    console.log("这是index"+index)
    console.log("这是index2"+index2)
    handleGroupClassDelete({id:GLOBAL.id}).then(res=>{
                console.log("这是返回值"+res.status)
                if(res.status==200){
                  if (index !== -1 && index2 !== -1) {
                    tableData.value.splice(index, 1);
                    currentTableData.value.splice(index2, 1);
                    handelCurrentChange3();
                    addEditDrawer.value=false
                    ElMessageBox.alert('删除成功！', '删除成功', {
                    type: 'success',
                    center:true,
                    })
                  }
                  else{
                    ElMessageBox.alert('删除失败！', '删除失败', {
                    type: 'error',
                    center:true,
                    })
                  }
                }
                else{
                  ElMessageBox.alert('删除失败！', '删除失败', {
                      type: 'error',
                      center:true,
                  })
                }
            })
  })
}


</script >
<style lang="less" scoped>
/deep/.el-color-picker__trigger{
      width:200px;
      height: 42px;
  }
  .form-div{
     border-bottom:1px solid #e0e0e0;
     padding:10px 50px; 
     font-size:24px;
     font-weight:200; 
     margin-bottom:20px
      
  }
  .w40{
      width:40%
  }
  .w20{
      width:20%;
      height: 40%;
  }
  
  .editor-big{
      // width: 90%;
      border: 1px solid #c2c2c2;
      margin-bottom: 20px;
      
  }
  .form-span{
      display: inline-block;
      color:#676a6c;
      background-color:#eee;
      height: 32px;
      padding: 0px 8px;
      border-radius: 0 5px 5px 0;
  }
.handle-box {
  margin-bottom: 20px;
}


.btn-opt {
  font-size: 13px;

  .el-button {
       margin-left: 3px;
       font-size: 13px;
       padding: 1px 6px;
  }
}
</style>
<style scoped>
    .pagination-container {
        margin-top: 15px;
        display: flex;
        justify-content: flex-end;
    }

    .add_GroupClass_form {
        margin: 10px 50px;
    }
</style>